import os
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['Times New Roman']

styles = ['-', '-.', '--', ':', 'solid',
          'dashed', 'dotted', 'dashdot', 'dashed']
markers = [' ', '>', '8', '*', 'x', '+', 'p', 'D']
colors = ["red", "orange", "blue", "c", "cyan",
          "brown", "mediumvioletred", "dodgerblue", "green"]


def load_a_day_res(filename):
    """
    读取一个结果文件
    """
    with open(filename, 'r') as f:
        row_list = f.read().splitlines()
    a_day_res = row_list[0].split('|')
    a_day_res = [int(float(i)) for i in a_day_res]
    return a_day_res



def make_res_table_statistics(filepath):
    """
    将某方法结果的所有天跑出来的结果汇总成一个table
    然后得出统计量，提供画图数据
    """
    file_list = os.listdir(filepath)

    server_num_list = []
    error_list = []
    for filename in file_list:
        error_data = load_a_day_res(filepath + '/' + filename)
        server_num = int(filename.split('.')[0])
        server_num_list.append(server_num)
        error_list.append(sum(error_data))
    res = (sorted(server_num_list), sorted(error_list, reverse = True))
    return res


def draw_plot(data_dict):
    """
    Input: 接受任意数量的数据，key充当画图的图例，value是画图用的原始数据
    """
    plt.figure(figsize=(8, 4))
    # 适配曲线数量
    count = 0
    for k, (server_num, error) in data_dict.items():
        print(k, server_num, error)
        # sns.lineplot(x, data, label=k, linestyle=styles[count], color=colors[count], linewidth=2.5)
        plt.plot(server_num, error, label=k, linestyle=styles[count], color=colors[count], linewidth=2.5)
        count += 1

    # plt.ylim(1000, 5000)
    plt.xlim(7000, 12000)
    plt.yticks(fontsize=27)
    plt.xticks(fontsize=27)
    plt.xlabel("Number of servers", fontsize=27)
    plt.ylabel("Error", fontsize=27)
    plt.grid()
    plt.legend(fontsize=27)
    # plt.legend(ncol=5, loc='lower center', bbox_to_anchor=(0.6, 0), fontsize=15, framealpha=0.5,
    #     borderpad=0.1,handletextpad=0.1, handlelength=1, columnspacing=0.2)
    return plt


if __name__ == "__main__":

    rand_error =  make_res_table_statistics('server_num_rand_result')

    ilp_error = make_res_table_statistics('server_num_ilp_result')
   
    pool_rand_error = make_res_table_statistics('server_num_resource_pool_rand_result')

    uniform_error = make_res_table_statistics('server_num_uniform_result')

    data_dict = {
        'RO-RP': pool_rand_error,
        'RR': rand_error,
        'TwithLB': ilp_error,
        'Uniform': uniform_error
    }

    pt = draw_plot(data_dict)
    pt.tight_layout()
    file_name = __file__.split('/')[-1].split('.')[0]
    pt.savefig(f"{file_name}.pdf", bbox_inches='tight')
    pt.show()
